<script setup lang="ts">
import type {
  MaintenanceQueryParams,
  MaintenanceRecord,
} from '#/api/maintenance';

import { onMounted, ref } from 'vue';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import {
  exportMaintenanceHistoryApi,
  getMaintenanceHistoryApi,
} from '#/api/maintenance';

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);

// 筛选表单
const searchForm = ref({
  licensePlate: '',
  driverName: '',
  requestType: '',
  approvalStatus: '',
  dateRange: [],
});

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});

// 维保记录列表
const maintenanceList = ref<MaintenanceRecord[]>([]);

// 排序状态
const sortState = ref({
  sortBy: 'apply_time',
  sortOrder: 'desc',
});

// 计算属性
const requestTypeOptions = ref([
  { label: '维修', value: '维修' },
  { label: '保养', value: '保养' },
]);

const approvalStatusOptions = ref([
  { label: '待审批', value: '待审批' },
  { label: '已批准', value: '已批准' },
  { label: '已驳回', value: '已驳回' },
]);

// 方法定义
const fetchData = async () => {
  loading.value = true;
  try {
    const params: MaintenanceQueryParams = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      sortBy: sortState.value.sortBy,
      sortOrder: sortState.value.sortOrder,
    };

    // 添加筛选条件
    if (searchForm.value.licensePlate) {
      params.licensePlate = searchForm.value.licensePlate;
    }
    if (searchForm.value.driverName) {
      params.driverName = searchForm.value.driverName;
    }
    if (searchForm.value.requestType) {
      params.requestType = searchForm.value.requestType;
    }
    if (searchForm.value.approvalStatus) {
      params.approvalStatus = searchForm.value.approvalStatus;
    }
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      params.startDate = searchForm.value.dateRange[0];
      params.endDate = searchForm.value.dateRange[1];
    }

    const response = await getMaintenanceHistoryApi(params);

    if (response.code === 0) {
      maintenanceList.value = response.data.items;
      pagination.value.total = response.data.total;
    } else {
      ElMessage.error('获取维保记录失败');
    }
  } catch {
    ElMessage.error('获取维保记录失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.value.page = 1; // 重置到第一页
  fetchData();
};

const handleReset = () => {
  searchForm.value = {
    licensePlate: '',
    driverName: '',
    requestType: '',
    approvalStatus: '',
    dateRange: [],
  };
  pagination.value.page = 1;
  fetchData();
};

const handleExport = async () => {
  exportLoading.value = true;
  try {
    const params: MaintenanceQueryParams = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      sortBy: sortState.value.sortBy,
      sortOrder: sortState.value.sortOrder,
    };

    // 添加筛选条件
    if (searchForm.value.licensePlate) {
      params.licensePlate = searchForm.value.licensePlate;
    }
    if (searchForm.value.driverName) {
      params.driverName = searchForm.value.driverName;
    }
    if (searchForm.value.requestType) {
      params.requestType = searchForm.value.requestType;
    }
    if (searchForm.value.approvalStatus) {
      params.approvalStatus = searchForm.value.approvalStatus;
    }
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      params.startDate = searchForm.value.dateRange[0];
      params.endDate = searchForm.value.dateRange[1];
    }

    const response = await exportMaintenanceHistoryApi(params);

    if (response.code === 0) {
      // 模拟文件下载
      const { fileName } = response.data;
      ElMessage.success(`导出成功，文件名：${fileName}`);
    } else {
      ElMessage.error('导出失败');
    }
  } catch {
    ElMessage.error('导出失败');
  } finally {
    exportLoading.value = false;
  }
};

const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchData();
};

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchData();
};

const handleSortChange = (sortData: any) => {
  const { prop, order } = sortData;
  sortState.value.sortBy = prop;
  sortState.value.sortOrder = order === 'ascending' ? 'asc' : 'desc';
  fetchData();
};

// 生命周期
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="maintenance-audit-record">
    <!-- 筛选区域 -->
    <ElCard class="filter-card">
      <ElForm :model="searchForm" inline>
        <ElFormItem label="车牌号">
          <ElInput
            v-model="searchForm.licensePlate"
            placeholder="支持模糊搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </ElFormItem>
        <ElFormItem label="申请司机">
          <ElInput
            v-model="searchForm.driverName"
            placeholder="支持模糊搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </ElFormItem>
        <ElFormItem label="申请类型">
          <ElSelect
            v-model="searchForm.requestType"
            placeholder="请选择"
            clearable
          >
            <ElOption
              v-for="option in requestTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="审批状态">
          <ElSelect
            v-model="searchForm.approvalStatus"
            placeholder="请选择"
            clearable
          >
            <ElOption
              v-for="option in approvalStatusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="申请日期">
          <ElDatePicker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="handleSearch">查询</ElButton>
          <ElButton @click="handleReset">重置</ElButton>
        </ElFormItem>
      </ElForm>
    </ElCard>

    <!-- 操作区域 -->
    <ElCard class="action-card">
      <ElButton type="primary" :loading="exportLoading" @click="handleExport">
        导出
      </ElButton>
    </ElCard>

    <!-- 数据表格 -->
    <ElCard class="data-card">
      <ElTable
        :data="maintenanceList"
        :loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <ElTableColumn prop="request_id" label="申请ID" sortable="custom" />
        <ElTableColumn prop="license_plate" label="车牌号" sortable="custom" />
        <ElTableColumn prop="driver_name" label="申请司机" />
        <ElTableColumn prop="request_type" label="申请类型" />
        <ElTableColumn prop="description" label="描述" min-width="200" />
        <ElTableColumn prop="approval_status" label="审批状态">
          <template #default="{ row }">
            <span
              :class="[
                row.approval_status === '已批准'
                  ? 'status-approved'
                  : row.approval_status === '待审批'
                    ? 'status-pending'
                    : 'status-rejected',
              ]"
            >
              {{ row.approval_status }}
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="cost" label="实际花费">
          <template #default="{ row }">
            {{ row.cost ? `¥${row.cost}` : '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="apply_time" label="申请时间" sortable="custom" />
        <ElTableColumn label="操作" width="120">
          <template #default="{ row }">
            <ElButton type="text" size="small">查看详情</ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 无数据提示 -->
      <div v-if="!loading && maintenanceList.length === 0" class="no-data">
        未查询到相关记录
      </div>

      <!-- 分页组件 -->
      <ElPagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[15, 20, 25, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </ElCard>
  </div>
</template>

<style scoped>
.maintenance-audit-record {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.action-card {
  margin-bottom: 16px;
}

.data-card {
  margin-bottom: 16px;
}

.status-approved {
  font-weight: 500;
  color: #67c23a;
}

.status-pending {
  font-weight: 500;
  color: #e6a23c;
}

.status-rejected {
  font-weight: 500;
  color: #f56c6c;
}

.no-data {
  padding: 40px 0;
  font-size: 14px;
  color: #909399;
  text-align: center;
}
</style>
